﻿using System;
using System.IO;
using IDataCenterContract;
using QueryResource.Common;
using Skynet.CommonLibrary.Extension;

namespace DevControlLibrary.Common
{
    class UpdateHelper
    {
        public static bool Update(Action beforAction)
        {
            try
            {
                string mainPath = System.Reflection.Assembly.GetEntryAssembly().Location;
                System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(mainPath);
                if (IsDown(name.Version.ToString(), Path.GetFileName(name.CodeBase)))
                {
                    if (File.Exists("Update.exe"))
                    {
                        if (beforAction != null)
                        {
                            beforAction();
                        }
                        ExecUpdate(mainPath);
                        return true;
                    }
                    MessageBoxHelper.Show("更新程序不存在，无法进行更新。");
                }
                else
                {
                    MessageBoxHelper.Show("已经是最新版本了");
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.Show("无法连接到更新服务器，无法更新。\r详细:" + ex.Message);
            }
            return false;
        }

        private static void ExecUpdate(string path)
        {
            string exePath = AppDomain.CurrentDomain.BaseDirectory + "\\Update.exe";
            exePath.StartProcessEx(path, AppDomain.CurrentDomain.BaseDirectory);
        }

        /// <summary>
        /// 查看是否有可下载的更新文件
        /// </summary>
        /// <param name="version">版本号</param>
        /// <param name="paraName">本程序名称</param>
        /// <returns></returns>
        public static bool IsDown(string version, string paraName)
        {
            IDownLoadFile down = DynamicInterfaceHelper.ConvertAnonymousTypeToInterface<IDownLoadFile>();
            return down.IsDown(version, paraName);
        }
    }
}
